<?php
namespace App\Http\Controllers\Admin;


use App\Models\ChannelSource;
use App\Models\Location;
use App\Models\Order;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 渠道
 *
 * @author Miluo Huang
 */
class ChannelSourceController extends Controller
{

	/**
	 * 渠道列表
	 */
	public function showSourceList(Request $request)
	{
		$data = ChannelSource::paginate();
		return view('admin.channel.source.list')->withData($data);
	}

	/**
	 * 渠道编辑
	 */
	public function showSourceEdit(Request $request){
		$data = ChannelSource::find($request->input('id'));
		return view('admin.channel.source.edit')->withData($data);
	}

	/**
	 * 渠道保存
	 */
	public function saveSourceEdit(Request $request){
		// 验证输入。
		$this->validate($request, [
			'name' => 'required|unique:channel_sources,name,' . $request->input('id', 0),
			'alias' => 'required|unique:channel_sources,alias,' . $request->input('id', 0),
		],[
			'name.required' => '渠道名必须填写！',
			'name.unique' => '渠道名已经存在！',
			'alias.required' => '渠道别名必须填写！',
			'alias.unique' => '渠道别名已经存在！',
		]);

		// 取得要编辑的模型。
		$data = $request->has('id') ? ChannelSource::find($request->input('id')) : null;
		if (is_null($data)) {
			$data = new ChannelSource();
		}

		// 编辑数据。
		$data->name = $request->input('name');
		$data->alias = $request->input('alias');
		$data->save();

		// 返回成功信息。
		return redirect()->back()->withMessageSuccess('保存成功。');
	}

	/**
	 * 渠道数据统计
	 */
	public function showSourceStatistics(Request $request){

		//取得省市区数据
		$province = Location::where('pid', 0)->get();
		$city = null;
		if ($request->has('province_id')) {
			$city = Location::where('pid', $request->input('province_id'))->get();
		}
		$area = null;
		if ($request->has('city_id')) {
			$area = Location::where('pid', $request->input('city_id'))->get();
		}
		$admin_user = Auth::admin()->user();
		if($admin_user->username == 'root' || $request->has('channel_ids')) {
            if ($request->has('channel_ids')) {
                $channel_ids = $request->input('channel_ids');
                Cache::forever('admin_channel_ids', $channel_ids);
            } else {
                $channel_ids = Cache::get('admin_channel_ids');
            }
        }else{
            $channel_ids = explode(',',$admin_user->channel);
            $channel_ids = array_filter($channel_ids);
            $channel_ids = array_unique($channel_ids);
        }
		if($channel_ids){
			$data = [];
			foreach($channel_ids as $key=>$item){
				$channel = ChannelSource::find($item);
				$order_count = Order::select('id')->where('channel_id',$item);
				$complate_count = Order::select('id')->where('channel_id',$item);
				$canceled_count = Order::select('id')->where('channel_id',$item);
				$deny_count = Order::select('id')->where('channel_id',$item);
				if($request->has('start_at')){
					$order_count = $order_count->where('created_at','>=',$request->input('start_at'));
					$complate_count = $complate_count->where('created_at','>=',$request->input('start_at'));
					$canceled_count = $canceled_count->where('created_at','>=',$request->input('start_at'));
					$deny_count = $deny_count->where('created_at','>=',$request->input('start_at'));
				}
				if($request->has('end_at')){
					$order_count = $order_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
					$complate_count = $complate_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
					$canceled_count = $canceled_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
					$deny_count = $deny_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
				}
				if($request->has('province_id')){
					$order_count = $order_count->where('province_id',$request->input('province_id'));
					$complate_count = $complate_count->where('province_id',$request->input('province_id'));
					$canceled_count = $canceled_count->where('province_id',$request->input('province_id'));
					$deny_count = $deny_count->where('province_id',$request->input('province_id'));
				}
				if($request->has('city_id')){
					$order_count = $order_count->where('city_id',$request->input('city_id'));
					$complate_count = $complate_count->where('city_id',$request->input('city_id'));
					$canceled_count = $canceled_count->where('city_id',$request->input('city_id'));
					$deny_count = $deny_count->where('city_id',$request->input('city_id'));
				}
				if($request->has('area_id')){
					$order_count = $order_count->where('area_id',$request->input('area_id'));
					$complate_count = $complate_count->where('area_id',$request->input('area_id'));
					$canceled_count = $canceled_count->where('area_id',$request->input('area_id'));
					$deny_count = $deny_count->where('area_id',$request->input('area_id'));
				}


				$order_count = $order_count->count();
				$complate_count = $complate_count->where('status','Completed')->count();
				$canceled_count = $canceled_count->where('status','Canceled')->count();
				$deny_count = $deny_count->where('status','Deny')->count();
				$data[$key]['channel_name'] = !is_null($channel) ? $channel->name : '';
				$data[$key]['order_count'] = $order_count;
				$data[$key]['complate_count'] = $complate_count;
				$data[$key]['canceled_count'] = $canceled_count;
				$data[$key]['deny_count'] = $deny_count;
				$data[$key]['complate'] = $order_count ? sprintf('%.2f',$complate_count/$order_count) * 100 : 0;
				$data[$key]['canceled'] = $order_count ? sprintf('%.2f',$canceled_count/$order_count) * 100 : 0;
				$data[$key]['deny'] = $order_count ? sprintf('%.2f',$deny_count/$order_count) * 100 : 0;
			}
		}else{
			$data = null;
		}
		$channel = ChannelSource::whereIn('id',$channel_ids)->get();
		return view('admin.channel.statistics.list')
				->withData($data)
				->withProvince($province)
				->withCity($city)
				->withArea($area)
				->withChannel($channel)
				->withGet($request->all());
	}

	/**
	 * 获取所有渠道
	 */
	public function getAll(){
        $admin_user = Auth::admin()->user();
        $channel_ids = explode(',',$admin_user->channel);
        $channel_ids = array_filter($channel_ids);
        $channel_ids = array_unique($channel_ids);
        $channel_ids[] = 0;
		$data = ChannelSource::orderby('id');
        if($admin_user->username != 'root'){
            $data = $data->whereIn('id',$channel_ids);
        }
        $data = $data->get();
		return view('admin.channel.statistics.all')->withData($data);
	}

	/**
	 * 渠道统计数据导出
	 */
	public function excel(Request $request){
        $admin_user = Auth::admin()->user();
        if($admin_user->username == 'root'  || $request->has('channel_ids')) {
            if ($request->has('channel_ids')) {
                $channel_ids = $request->input('channel_ids');
                Cache::forever('admin_channel_ids', $channel_ids);
            } else {
                $channel_ids = Cache::get('admin_channel_ids');
            }
        }else{
            $channel_ids = explode(',',$admin_user->channel);
            $channel_ids = array_filter($channel_ids);
            $channel_ids = array_unique($channel_ids);
        }
		if($channel_ids){
			$data = [];
			foreach($channel_ids as $key=>$item){
				$channel = ChannelSource::find($item);
				$order_count = Order::select('id')->where('channel_id',$item);
				$complate_count = Order::select('id')->where('channel_id',$item);
				$canceled_count = Order::select('id')->where('channel_id',$item);
				$deny_count = Order::select('id')->where('channel_id',$item);
				if($request->has('start_at')){
					$order_count = $order_count->where('created_at','>=',$request->input('start_at'));
					$complate_count = $complate_count->where('created_at','>=',$request->input('start_at'));
					$canceled_count = $canceled_count->where('created_at','>=',$request->input('start_at'));
					$deny_count = $deny_count->where('created_at','>=',$request->input('start_at'));
				}
				if($request->has('end_at')){
					$order_count = $order_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
					$complate_count = $complate_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
					$canceled_count = $canceled_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
					$deny_count = $deny_count->where('created_at','<=',$request->input('end_at').' 23:59:59');
				}
				if($request->has('province_id')){
					$order_count = $order_count->where('province_id',$request->input('province_id'));
					$order_count = $order_count->where('province_id',$request->input('province_id'));
					$order_count = $order_count->where('province_id',$request->input('province_id'));
					$order_count = $order_count->where('province_id',$request->input('province_id'));
				}
				if($request->has('city_id')){
					$order_count = $order_count->where('city_id',$request->input('city_id'));
					$order_count = $order_count->where('city_id',$request->input('city_id'));
					$order_count = $order_count->where('city_id',$request->input('city_id'));
					$order_count = $order_count->where('city_id',$request->input('city_id'));
				}
				if($request->has('area_id')){
					$order_count = $order_count->where('area_id',$request->input('area_id'));
					$order_count = $order_count->where('area_id',$request->input('area_id'));
					$order_count = $order_count->where('area_id',$request->input('area_id'));
					$order_count = $order_count->where('area_id',$request->input('area_id'));
				}


				$order_count = $order_count->count();
				$complate_count = $complate_count->where('status','Completed')->count();
				$canceled_count = $canceled_count->where('status','Canceled')->count();
				$deny_count = $deny_count->where('status','Deny')->count();
				$data[$key]['渠道名'] = !is_null($channel) ? $channel->name : '';
				$data[$key]['订单数'] = $order_count ? $order_count : '0';
				$data[$key]['实际交易数'] = $complate_count ? $complate_count : '0';
				$data[$key]['取消定单数'] = $canceled_count ? $canceled_count : '0';
				$data[$key]['拒签数'] = $deny_count;
				$data[$key]['实际交易比率'] = $order_count ? sprintf('%.2f',$complate_count/$order_count)*100 . '%' : '0%';
				$data[$key]['取消定单比率'] = $order_count ? sprintf('%.2f',$canceled_count/$order_count)*100 . '%' : '0%';
				$data[$key]['拒签比率'] = $order_count ? sprintf('%.2f',$deny_count/$order_count)*100 . '%' : '0%';
			}
		}else{
			$data = [];
		}

		Excel::create('渠道数据统计' . date('YmdHis'), function ($excel) use ($data) {
			$excel->sheet('Excel sheet', function ($sheet) use ($data) {
				$sheet->fromArray($data);
			});
		})->export('xls');
	}

}
